<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2022/2/23
 * Time: 14:26
 */

namespace app\admin\controller;


use think\Db;
use think\Request;

class Orderb extends Base
{
    /**
     * 脖脸皮订单列表
     * @return mixed|\think\response\Json
     */
    public function index(){
        if(request()->isAjax ()){
            $keyword = trim(input('keyword'), ' '); // 订单号或ID
            $bo_status = input('bo_status');
            $is_pay = input('is_pay');
            $start_time = input('start_time');
            $end_time = input('end_time');
            $keyword_user = input('keyword_user');
            
            $where = [];
            if(isset($keyword) && $keyword != ''){
                $where['bo_id|bo_number'] = ['like', '%' . $keyword . '%'];
            }
            if(isset($keyword_user) && $keyword_user != ''){
                $where['user_real_name|user_phone'] = ['like', '%' . $keyword_user . '%'];
            }
            if(isset($bo_status) && $bo_status != ''){
                if($bo_status != -1){
                    $where['bo_status'] = $bo_status;
                }
            }else{
                $where['bo_status'] = 2;
            }
            if(isset($is_pay) && $is_pay != ''){
                $where['bo_is_pay'] = $is_pay;
            }
            if(isset($start_time) && $start_time != '' && isset($end_time) && $end_time != ''){
                $where['bo_create_time'] = ['between', [$start_time, $end_time]];
            }
            if(isset($start_time) && $start_time != '' && isset($end_time) && $end_time == ''){
                $where['bo_create_time'] = ['>=', $start_time];
            }
            if(isset($start_time) && $start_time == '' && isset($end_time) && $end_time != ''){
                $where['bo_create_time'] = ['<=', $end_time];
            }
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::table('up_bo_order')
                ->join('up_u_user', 'bo_user_id = user_id', 'LEFT')
                ->join('up_user_address', 'addr_id = bo_addr_id', 'LEFT')
                ->join('up_area u1', 'u1.district_id = addr_sheng', 'LEFT')
                ->join('up_area u2', 'u2.district_id = addr_shi', 'LEFT')
                ->join('up_area u3', 'u3.district_id = addr_qu', 'LEFT')
                ->where($where)
                ->count('bo_id');
            $lists = Db::table('up_bo_order')
                ->join('up_u_user', 'bo_user_id = user_id', 'LEFT')
                ->join('up_user_address', 'addr_id = bo_addr_id', 'LEFT')
                ->join('up_area u1', 'u1.district_id = addr_sheng', 'LEFT')
                ->join('up_area u2', 'u2.district_id = addr_shi', 'LEFT')
                ->join('up_area u3', 'u3.district_id = addr_qu', 'LEFT')
                ->field('bo_id, bo_number, bo_is_pay, bo_total_price, bo_remark, bo_status, 
                bo_create_time, bo_express_company, bo_express_code, user_real_name, user_phone, 
                bo_addr_id, concat(u1.district,"",u2.district, "", u3.district, "", addr_address) address, 
                addr_user_name, addr_user_phone, user_shop_name, bo_cancel_reason')
                ->where($where)
                ->order('bo_create_time desc')
                ->page($Nowpage,$limits)
                ->select();

            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        return $this->fetch();
    }
    
    /**
     * 商品列表
     * @return mixed|\think\response\Json
     */
    public function orderGoods(){
        if(Request::instance()->isAjax()){
            $where['boi_order_id'] = session('bo_id');
            
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::table('up_bo_order_info')
                ->join('up_bo_goods', 'bg_id = boi_goods_id', 'LEFT')
                ->where($where)
                ->count();// 获取总条数
            $lists = Db::table('up_bo_order_info')
                ->join('up_bo_goods', 'bg_id = boi_goods_id', 'LEFT')
                ->field('bg_name, bg_thumb, bg_price, boi_goods_number, boi_goods_price, bg_spec, bg_type')
                ->where($where)
                ->order('boi_id asc')
                ->page($Nowpage,$limits)
                ->select();
            
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        $bo_id = input('bo_id');
        if(isset($bo_id) && $bo_id != ''){
            session('bo_id', $bo_id);
        }
        $order = Db::table('up_bo_order')
            ->join('up_u_user', 'bo_user_id = user_id', 'LEFT')
            ->join('up_user_address', 'addr_id = bo_addr_id', 'LEFT')
            ->join('up_area u1', 'u1.district_id = addr_sheng', 'LEFT')
            ->join('up_area u2', 'u2.district_id = addr_shi', 'LEFT')
            ->join('up_area u3', 'u3.district_id = addr_qu', 'LEFT')
            ->field('bo_total_price, bo_total_number, u1.district sheng, 
            u2.district shi, u3.district qu, addr_address, 
            addr_user_name, addr_user_phone')
            ->where('bo_id', $bo_id)
            ->find();
        return $this->fetch('', ['order' => $order]);
    }
    
    /**
     * 取消订单
     * @return mixed|\think\response\Json
     */
    public function orderCancel(){
        $bo_id = input('bo_id');
        if(Request::instance()->isPost()){
            $bo_cancel_reason = input('reason');
            $order_info = Db::table('up_bo_order_info')
                ->where('boi_order_id', $bo_id)
                ->field('boi_goods_id, boi_goods_number')
                ->select();
            $order = Db::table('up_bo_order')
                ->where('bo_id', $bo_id)
                ->field('bo_user_id, bo_total_price, bo_status')
                ->find();
            if($order['bo_status'] != 1 && $order['bo_status'] != 2) return json(['code' => 100, 'msg' => '订单状态异常，请刷新列表页重试']);
    
            $update = [
                'bo_status' => 6,
                'bo_cancel_time' => date('Y-m-d H:i:s'),
                'bo_cancel_reason' => $bo_cancel_reason
            ];
            
            Db::startTrans();
            try{
                // 修改订单状态
                Db::table('up_bo_order')->where('bo_id', $bo_id)->update($update);
                
                // 释放库存&减销量
                foreach($order_info as $k => $v){
                    Db::table('up_bo_goods')
                        ->where('bg_id', $v['boi_goods_id'])
                        ->inc('bg_stock', $v['boi_goods_number'])
                        ->dec('bg_sale_number', $v['boi_goods_number'])
                        ->update();
                }
                
                // 如果是待发货的订单，则需要退还已支付的积分，并进入积分明细表
                if($order['bo_status'] == 2){
                    $user = Db::table('up_u_user')
                        ->where('user_id', $order['bo_user_id'])
                        ->field('user_bo_balance')
                        ->find();

                    $desc = '取消订单退还';
                    if($bo_cancel_reason){
                        $desc = $desc . '-' . $bo_cancel_reason;
                    }
                    $this->insertBoInte($order['bo_user_id'], 1, $desc, $order['bo_total_price'], $user['user_bo_balance'], $bo_id);

                    Db::table('up_u_user')
                        ->where('user_id', $order['bo_user_id'])
                        ->inc('user_bo_other_balance', $order['bo_total_price'])
                        ->inc('user_bo_balance', $order['bo_total_price'])
                        ->update();
                }
                
                Db::commit();
                return json(['code' => 200, 'msg' => '操作成功']);
            }catch(\Exception $e){
                Db::rollback();
                return json(['code' => 100, 'msg' => $e->getMessage()]);
            }
        }
        return $this->fetch('', ['bo_id' => $bo_id]);
    }
    
    /**
     * 发货
     * @return mixed|\think\response\Json
     */
    public function orderSend(){
        $bo_id = input('bo_id');
        if(Request::instance()->isPost()){
            $bo_express_company = trim(input('bo_express_company'));
            $bo_express_code = trim(input('bo_express_code'));
            
            $order_status = Db::table('up_bo_order')->where('bo_id', $bo_id)->value('bo_status');
            if($order_status != 2) return json(['code' => 100, 'msg' => '订单状态异常，请刷新列表页重试']);
            
            $res = Db::table('up_bo_order')
                ->update([
                    'bo_id' => $bo_id,
                    'bo_status' => 3,
                    'bo_send_time' => date('Y-m-d H:i:s'),
                    'bo_express_company' => $bo_express_company,
                    'bo_express_code' => $bo_express_code
                ]);
            if($res){
                return json(['code' => 200, 'msg' => '操作成功']);
            }else{
                return json(['code' => 100, 'msg' => '操作失败']);
            }
        }
        $wuliu = Db::table('up_about')->where('id', 7)->value('content');
        return $this->fetch('', ['bo_id' => $bo_id, 'wuliu' => $wuliu]);
    }
    
    /**
     * 编辑物流
     * @return mixed|\think\response\Json
     */
    public function updateWuLiu(){
        $bo_id = input('bo_id');
        if(Request::instance()->isPost()){
            $bo_express_company = trim(input('bo_express_company'));
            $bo_express_code = trim(input('bo_express_code'));
            
            $res = Db::table('up_bo_order')
                ->update([
                    'bo_id' => $bo_id,
                    'bo_express_company' => $bo_express_company,
                    'bo_express_code' => $bo_express_code
                ]);
            if($res){
                return json(['code' => 200, 'msg' => '操作成功']);
            }else{
                return json(['code' => 100, 'msg' => '操作失败']);
            }
         }
        $wuliu = Db::table('up_bo_order')->where('bo_id', $bo_id)->field('bo_express_company, bo_express_code')->find();
        return $this->fetch('', ['bo_id' => $bo_id, 'wuliu' => $wuliu]);
    }
    
    /**
     * 确认收货
     * @return \think\response\Json
     */
    public function orderAffirm(){
        $bo_id = input('id');
        $order = Db::table('up_bo_order')
            ->where('bo_id', $bo_id)
            ->field('bo_status, bo_total_price, bo_user_id')
            ->find();
        if($order['bo_status'] != 3) return json(['code' => 100, 'msg' => '订单状态异常']);

        // 修改订单状态
        $res = Db::table('up_bo_order')
            ->update([
                'bo_id' => $bo_id,
                'bo_status' => 4,
                'bo_over_time' => date('Y-m-d H:i:s')
            ]);
        if($res){
            return json(['code' => 200, 'msg' => '操作成功']);
        }else{
            return json(['code' => 100, 'msg' => '操作失败']);
        }
    }
    
    /**
     * 导出
     * @return \think\response\Json
     */
    public function outExcel(){
        set_time_limit(0);
        $order_ids = input('ids');

        $where = [];
        if($order_ids == -1){
            $keyword = trim(input('keyword'), ' '); // 订单号或ID
            $bo_status = input('bo_status');
            $is_pay = input('is_pay');
            $start_time = input('start_time');
            $end_time = input('end_time');
            $keyword_user = input('keyword_user');

            if(isset($keyword) && $keyword != ''){
                $where['bo_id|bo_number'] = ['like', '%' . $keyword . '%'];
            }
            if(isset($keyword_user) && $keyword_user != ''){
                $where['user_real_name|user_phone'] = ['like', '%' . $keyword_user . '%'];
            }
            if(isset($bo_status) && $bo_status != ''){
                if($bo_status != -1){
                    $where['bo_status'] = $bo_status;
                }
            }else{
                $where['bo_status'] = 2;
            }
            if(isset($is_pay) && $is_pay != ''){
                $where['bo_is_pay'] = $is_pay;
            }
            if(isset($start_time) && $start_time != '' && isset($end_time) && $end_time != ''){
                $where['bo_create_time'] = ['between', [$start_time, $end_time]];
            }
            if(isset($start_time) && $start_time != '' && isset($end_time) && $end_time == ''){
                $where['bo_create_time'] = ['>=', $start_time];
            }
            if(isset($start_time) && $start_time == '' && isset($end_time) && $end_time != ''){
                $where['bo_create_time'] = ['<=', $end_time];
            }
        }else{
            if($order_ids == ''){
                return json(['code' => 100, 'msg' => '请选择需要导出的数据']);
            }
            $where['bo_id'] = ['IN', $order_ids];
        }

        $lists = Db::table('up_bo_order')
            ->join('up_u_user', 'bo_user_id = user_id', 'LEFT')
            ->join('up_user_address', 'addr_id = bo_addr_id', 'LEFT')
            ->join('up_area u1', 'u1.district_id = addr_sheng', 'LEFT')
            ->join('up_area u2', 'u2.district_id = addr_shi', 'LEFT')
            ->join('up_area u3', 'u3.district_id = addr_qu', 'LEFT')
            ->field('bo_id, bo_number, bo_is_pay, bo_total_price, bo_remark, bo_status, bo_create_time, 
            bo_express_company, bo_express_code, user_real_name, user_phone, bo_addr_id, bo_pay_time, 
            bo_send_time, bo_over_time, bo_close_time, bo_cancel_time, addr_user_name, addr_user_phone, 
            concat(u1.district,"",u2.district, "", u3.district, "", addr_address) address, 
            user_shop_name')
            ->where($where)
            ->order('bo_create_time desc')
            ->select();
        $goods = Db::table('up_bo_order_info')
            ->join('up_bo_goods', 'boi_goods_id = bg_id', 'LEFT')
            ->where('boi_order_id', 'IN', $order_ids)
            ->field('bg_name, bg_spec, boi_goods_number, boi_order_id')
            ->select();
        foreach($lists as $k => $v){
            // 物流单号
            $lists[$k]['bo_express_code'] = "\t". ltrim($v['bo_express_code'], ',') ."\t";
            // 下单人手机号
            $lists[$k]['user_phone'] = "\t" . $v['user_phone'] . "\t";
            // 总金额
            $lists[$k]['bo_total_price'] = "\t" . $v['bo_total_price'] . "\t";
            // 支付状态
            $lists[$k]['bo_is_pay'] = $v['bo_is_pay'] == 1 ? '未支付' : '已支付';
            // 订单状态
            switch($v['bo_status']){
                case 1:
                    $lists[$k]['bo_status'] = '待付款';
                    break;
                case 2:
                    $lists[$k]['bo_status'] = '待发货';
                    break;
                case 3:
                    $lists[$k]['bo_status'] = '待收货';
                    break;
                case 4:
                    $lists[$k]['bo_status'] = '已完成';
                    break;
                case 5:
                    $lists[$k]['bo_status'] = '已关闭';
                    break;
                case 6:
                    $lists[$k]['bo_status'] = '已取消';
                    break;
                default:
                    $lists[$k]['bo_status'] = '未知';
            }

            // 商品
            $str = '';
            foreach($goods as $kk => $vv){
                if($v['bo_id'] == $vv['boi_order_id']){
                    $str .= "{$vv['bg_name']}--{$vv['bg_spec']}*{$vv['boi_goods_number']}\n";
                }
            }
            $lists[$k]['order_goods'] = rtrim($str, "\n");
        }
        $cellname = [
            ['bo_id', '订单ID', 10, 'LEFT'],
            ['bo_number', '订单编号', 20, 'LEFT'],
            ['order_goods', '商品', 30, 'LEFT'],
            ['bo_is_pay', '支付状态', 15, 'LEFT'],
            ['bo_total_price', '订单总金额', 15, 'LEFT'],
            ['bo_status', '订单状态', 15, 'LEFT'],
            ['user_real_name', '下单用户', 15, 'LEFT'],
            ['user_phone', '下单手机号', 15, 'LEFT'],
            ['bo_remark', '备注', 20, 'LEFT'],
            ['address', '收获地址', 30, 'LEFT'],
            ['addr_user_name', '收货人', 15, 'LEFT'],
            ['addr_user_phone', '收货人手机号', 15, 'LEFT'],
            ['user_shop_name', '店铺名称', 15, 'LEFT'],
            ['bo_express_company', '快递公司', 15, 'LEFT'],
            ['bo_express_code', '快递单号', 20, 'LEFT'],
            ['bo_create_time', '下单时间', 20, 'LEFT'],
            ['bo_pay_time', '付款时间', 20, 'LEFT'],
            ['bo_send_time', '发货时间', 20, 'LEFT'],
            ['bo_over_time', '收货时间', 20, 'LEFT'],
            ['bo_cancel_time', '取消时间', 20, 'LEFT'],
            ['bo_close_time', '关闭时间', 20, 'LEFT']
        ];
        $res = exportExcelZhy('脖脸皮订单', 'Bo_order', $cellname, $lists);
        return json($res);
    }
}